import json
import time
import random
from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,marshal, reqparse
from alipay import AliPay
from models.orders import OrderModel
# from common.utlis.login_utlis import login_required
from common.utlis.jwt_util import check_token
from common.utlis.login_utlis import login_required
from models.users import VipModel
from models import db


pay_bp = Blueprint('pay',__name__, url_prefix='/pay')

api = Api(pay_bp)


class CreateOrderResource(Resource):

    # @login_required
    def get(self):
        """创建订单"""
        # 思路分析
        """
        首先要先登录:
        登录成功的
        1. 随机生成订单号: 时间戳+用户id+随机数组成
        2. 写入数据库: 订单号, 用户信息, 
        """
        # 接收前端传来的价格, 会员等级
        parser = reqparse.RequestParser()
        parser.add_argument('token')

        args = parser.parse_args()
        token = args.get('token')
        print('token>>>', token)
        payload = check_token(token)
        if payload:
            uid = payload['id']
        # 订单id
        order_id = str(time.time()*1000000)+ str(uid)+ str(random.randint(100000,999999))
        # OrderModel(order_id=order_id,user_id=uid,
        #            )
        return jsonify(message='ok', data={"order":order_id},code=200)


class AliPayResource(Resource):
    """支付宝支付"""
    def __init__(self):
        # 获取公钥和私钥
        self.app_private_key_string = open('common/pay_key/app_private_key.pem').read()
        self.alipay_public_key_string = open('common/pay_key/app_public_key.pem').read()
        # 创建阿里的对象
        self.aliay = AliPay(
            appid="2021000119634123",
            app_notify_url='http://127.0.0.1:8080/callback',  # 默认回调url
            app_private_key_string=self.app_private_key_string,
            alipay_public_key_string=self.alipay_public_key_string,
            sign_type="RSA2",
            debug=True
        )
        self.alipay_getway = 'https://openapi.alipaydev.com/gateway.do'

    @login_required
    def post(self):
        """创建订单"""
        parser = reqparse.RequestParser()
        parser.add_argument('order')
        parser.add_argument('price')
        parser.add_argument('token')
        parser.add_argument('record')
        args = parser.parse_args()
        order_id = args.get('order')
        price = args.get('price')
        grade = args.get('record')
        token = args.get('token')
        # print('token>>>>>>>>>>', token)
        # print('price>>>>>>>>', price)
        print('order>>>', order_id)
        try:
            payload = check_token(token)
            print(payload)
        except Exception as e:
            # 校验错误,先登录
            return jsonify(message='请先登录', code=401)
        # 获取用户id
        uid = payload['id']
        print('uid>>>', uid)
        if grade == '免费':
            grade = 0
        if grade == '普通会员':
            grade = 1
        if grade == '高级会员':
            grade = 2
        vip = VipModel.query.filter_by(level=grade).first()
        # print('grade》》》', grade)
        # print('vip', vip)
        try:
            order = OrderModel(
                order_id=order_id,
                user_id=uid,
                vip=vip.id,
                trade_no=order_id,
                pay_amount=price
            )
            db.session.add(order)
            db.session.commit()
            return jsonify(message="创建订单成功", code=200)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message="创建订单失败", code=500)

    @login_required
    def get(self):
        """获取支付宝登录的url"""
        parser = reqparse.RequestParser()
        parser.add_argument('order')
        parser.add_argument('price')
        args = parser.parse_args()
        order_id = args.get('order')
        price = args.get('price')
        #
        data = self.aliay.api_alipay_trade_page_pay(
            subject="实验楼购买会员消费",
            out_trade_no="%s" % order_id,
            total_amount=price,
            return_url='http://127.0.0.1:8080/callback'
        )
        url = self.alipay_getway + '?' + data
        print('url>>>', url)
        return jsonify(message="请求成功，跳转支付页面", data=url, code=200)


class CheckAlipay(Resource):
    def get(self):
        """验证支付是否成功"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('data')
        args = parser.parse_args()
        token = args.get('token')
        data_ = args.get('data') # 回调的查询字符串
        print('token, data_', token,'\n', data_)
        try:
            payload = check_token(token)
        except Exception as e:
            # 校验错误,先登录
            return jsonify(message='请先登录', code=401)
        # 校验知否是真正支付成功,
        # print("data_", data_)
        data = json.loads(data_)
        signature = data.pop("sign")
        # print('data>>', data)
        # print('sign>>>',signature)
        alipay = AliPayResource().alipay
        # 验证是否支付成功
        result = alipay.verify(data, signature)
        # print("支付的结果>>",result)
        if result:
            return jsonify(message="支付成功",code=200)
        else:
            return jsonify(message="支付失败", code=500)


class ChangeOrderStatus(Resource):
    def get(self):
        """修改订单状态"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('order')
        args = parser.parse_args()
        token = args.get('token')
        order_id = args.get('order')  # 回调的查询字符串
        try:
            payload = check_token(token)
        except Exception as e:
            # 校验错误,先登录
            return jsonify(message='请先登录', code=401)
        try:
            OrderModel.query.filter_by(order_id=order_id,user_id= payload['id']).update({'status':1})
            db.session.commit()
            return jsonify(message="支付成功", code=200)
        except Exception as e:
            print('错误>>>', e)
            return jsonify(message="修改订单状态失败", code=500)


api.add_resource(CreateOrderResource,'/create_order')

api.add_resource(AliPayResource, '/alipay')

api.add_resource(CheckAlipay,'/check_pay')
api.add_resource(ChangeOrderStatus,'/get_alipay')